#!/bin/sh

cd ${JIANMU_WORKSPACE} && pwd

if [[ ! -z "${JIANMU_DOCKER_USERNAME}" ]]; then 
	docker login -u ${JIANMU_DOCKER_USERNAME} -p ${JIANMU_DOCKER_PASSWORD} ${JIANMU_REGISTRY_ADDRESS}; 
fi

set -x 

if [[ ! -z "${JIANMU_PLATFORM}" ]]; then
        { # try
            docker run -it --rm --privileged tonistiigi/binfmt --install all || true
            builder_name="jianmu-builder-`cat /proc/sys/kernel/random/uuid`"
            docker buildx ls
            docker buildx create --use --name ${builder_name} --driver docker-container 
            docker buildx build --no-cache -f ${JIANMU_DOCKER_FILE} -t ${JIANMU_IMAGE_NAME}:${JIANMU_IMAGE_TAG} --platform ${JIANMU_PLATFORM} --push ${JIANMU_DOCKER_BUILD_PATH}
            docker buildx rm ${builder_name} || true
            docker ps|grep ${builder_name}|grep buildkit|awk '{ print "docker stop " $1 " && docker rm " $1}'| sh || true
            exit(0)
        } || {
            docker buildx rm ${builder_name} || true
            docker ps|grep ${builder_name}|grep buildkit|awk '{ print "docker stop " $1 " && docker rm " $1}'| sh || true
            exit(1)
        }
else
        docker build --no-cache -f ${JIANMU_DOCKER_FILE} -t ${JIANMU_IMAGE_NAME}:${JIANMU_IMAGE_TAG} ${JIANMU_DOCKER_BUILD_PATH} && docker push ${JIANMU_IMAGE_NAME}:${JIANMU_IMAGE_TAG}    
fi
